<?php
class MenuController extends Zend_Controller_Action
{
	public function indexAction()
	{
		$content_root = '';
		$q = Doctrine_Query::create()
			->from('TTF_Model_Categories c')
			->where('c.parent_id = 0');
		$result = $q->fetchArray();
		foreach ($result as $root) {
			list($content) = $this->get_children_of_category($root['id']);
			if ($this->fetch_child($child['id']) == 0) {
				if ($this->haveFoods($root['id'])) {
					$content_root .= "<li><a href='/san-pham/" . $root['id'] . "' >" . $root['name'] . "</a>";
				} else {
					$content_root .= "<li><span>" . $root['name'] . "</span>";
				}
			} else {
				if ($this->haveFoods($root['id'])) {
					$content_root .= "<li><a href='/san-pham/" . $root['id'] . "' >" . $root['name'] . "</a>";
				} else {
					$content_root .= "<li><span>" . $root['name'] . "</span>";
				}
			}
			$content_root .= $content;
			$content_root .= "</li>\n";
		}	
		$this->view->categories = $content_root;
	}
			
	public function get_children_of_category($category_id) 
	{
		if (!isset($content)) {
			$content = '';
		}
		
		$q = Doctrine_Query::create()
			->from('TTF_Model_Categories c')
			->where('c.parent_id = ?', $category_id);
		$result = $q->fetchArray();
		if (count($result) > 0) {
			foreach ($result as $child) {
				list($content2) = $this->get_children_of_category($child['id']);
				if ($this->fetch_child($child['id']) == 0) {
					if ($this->haveFoods($child['id'])) {
						$content .= "<li><a href='/san-pham/" . $child['id'] . "' >" . $child['name'] . "</a>";
					} else {
						$content .= "<li><span>" . $child['name'] . "</span>";
					}
				} else {
					if ($this->haveFoods($child['id'])) {
						$content .= "<li><a href='/san-pham/" . $child['id'] . "' >" . $child['name'] . "</a>";
					} else {
						$content .= "<li><span>" . $child['name'] . "</span>";
					}
				}			
				$content .= $content2;
				$content .= "</li>\n";
			}
			$content = "<ul>" . $content . "</ul>";
		}
		return array($content);
	}
	
	public function fetch_child($parent)
	{
		$q = Doctrine_Query::create()
			->from('TTF_Model_Categories c')
			->where('c.parent_id = ?', $parent);
		$results = $q->fetchArray();
		$list = array();
		foreach ($results as $result) {
			$list[] = (int)$result['id'];
			$list = array_merge($list, $this->fetch_child($result['id']));
		}
		return $list;
	}
	
	public function haveFoods($category_id)
	{
		$q = Doctrine_Query::create()
			->from('TTF_Model_Foods f')
			->where('f.category_id = ?', $category_id);
		return $q->fetchArray();
	}
}